package com.example.safeassistan.home.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.base.BaseModel;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.hiddendanger.activity.HiddendangerUnSubmit;
import com.example.safeassistan.home.fragment.BackLogFragment;
import com.example.safeassistan.home.view.DateSelectDialog;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.utile.JsonUtils;
import com.google.android.material.tabs.TabLayout;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TemporaryTask extends BaseActivity implements View.OnClickListener {
    private RelativeLayout rlStartTime,rlEndTime,rlExcuteUnit,rlCheckedDePart,rlExcuteUnitPerson,
            rlCheckType,rlExcuteDegree,rlJoinPerson,rlCheckTable;
    private TextView tvSceneTask,tvFoundationTask,tvPublish,tvExcuteUnit,tvCheckedPart,
            tvStartTime,tvEndTime,tvExcuteUnitPerson,tvCheckType,tvExcuteUnitDegree,
            tvJoinPerson,tvCheckTable;
    private EditText etTaskName,etTaskIntro;
    private static final Integer REQUESTCODE=10001;
    private static final Integer REQUESTCODE2=10002;
    private static final Integer REQUESTCODE1=10000;
    private static final Integer REQUESTCODE3=10003;
    private static final Integer REQUESTCODE4=10004;
    private static final Integer REQUESTCODE5=10005;
    private static final Integer REQUESTCODE6=10006;

    private String checkGroup="";//执行单位
    private String examinedGroup="";//受检单位
    private String startTime="";//起始时间
    private String endTime="";//结束时间
    private String checkModel="2";//任务类型 1、现场 2、基础
    private String defName="";//任务名称
    private String defDesc="";//任务描述
    private String checkPerson="";//执行人员
    private String checkParticipant="";//参与人员id
    private String checkType="";//检查类型
    private String checkPosition="";//执行岗位
    private String checkTable="";//检查表id

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, TemporaryTask.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rlStartTime:
                TimePickerView startTimes = new TimePickerBuilder(TemporaryTask.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
                        tvStartTime.setText(simpleDateFormat.format(date));
                        startTime=simpleDateFormat.format(date);
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .isDialog(true)
                        .setSubmitText("确定")//确认按钮文字
                        .setTitleSize(18)//标题文字大小
                        .setTitleColor(getResources().getColor(R.color.white))
                        .setTitleText("起始时间")
                        .setContentTextSize(17)
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(true)//是否循环滚动
                        .setTextColorOut(getResources().getColor(R.color.gray6))
                        .setTextColorCenter(getResources().getColor(R.color.blue_3B5BEA))
                        .setSubmitColor(getResources().getColor(R.color.white))//确定按钮文字颜色
                        .setLabel("年", "月", "日", "时", "分", "秒")//默认设���为年月日时分秒
                        .isCenterLabel(false) //是否只显示中间选中项的 label 文字，false 则每项 item 全部都带有 label。
                        .build();
                startTimes.show();
                break;
            case R.id.rlEndTime:
                TimePickerView endTimes = new TimePickerBuilder(TemporaryTask.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
                        tvEndTime.setText(simpleDateFormat.format(date));
                        endTime=simpleDateFormat.format(date);
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .isDialog(true)
                        .setSubmitText("确定")//确认按钮文字
                        .setTitleSize(18)//标题文字大小
                        .setTitleColor(getResources().getColor(R.color.white))
                        .setTitleText("结束时间")
                        .setContentTextSize(17)
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(true)//是否循环滚动
                        .setTextColorOut(getResources().getColor(R.color.gray6))
                        .setTextColorCenter(getResources().getColor(R.color.blue_3B5BEA))
                        .setSubmitColor(getResources().getColor(R.color.white))//确定按钮文字颜色
                        .setLabel("年", "月", "日", "时", "分", "秒")//默认设���为年月日时分秒
                        .isCenterLabel(false) //是否只显示中间选中项的 label 文字，false 则每项 item 全部都带有 label。
                        .build();
                endTimes.show();
                break;
            case R.id.rlExcuteUnit:
              //  ExcuteUnitList.actionStart(getContext());
                Intent intent=new Intent(TemporaryTask.this, AuthorizeDepartment.class);
                intent.putExtra("flag", REQUESTCODE);
                startActivityForResult(intent, REQUESTCODE);
                break;
            case R.id.tvSceneTask:
                reSetStatus();
                checkModel="1";
                tvSceneTask.setTextColor(getResources().getColor(R.color.blue_3B5BEA));
                tvSceneTask.setBackgroundResource(R.drawable.stoke_solid_blue_bg_5);
                break;
            case R.id.tvFoundationTask:
                reSetStatus();
                checkModel="2";
                tvFoundationTask.setTextColor(getResources().getColor(R.color.blue_3B5BEA));
                tvFoundationTask.setBackgroundResource(R.drawable.stoke_solid_blue_bg_5);
                break;
            case R.id.tvPublish:
                //发布
                submitData();
                break;
            case R.id.rlCheckedDePart:
                Intent intent1=new Intent(TemporaryTask.this, AuthorizeDepartment.class);
                intent1.putExtra("flag", REQUESTCODE1);
                startActivityForResult(intent1, REQUESTCODE1);
                break;
            case R.id.rlExcuteUnitPerson:
                if (checkPosition.equals("")||checkGroup.equals("")){
                    Toast.makeText(TemporaryTask.this,"请先选择相关部门和岗位",Toast.LENGTH_SHORT);
                    return;
                }else {
                    Intent intent2=new Intent(TemporaryTask.this, ActivityUserList.class);
                    intent2.putExtra("flag", REQUESTCODE2);
                    intent2.putExtra("positionId",checkPosition);
                    intent2.putExtra("departId",checkGroup);
                    startActivityForResult(intent2, REQUESTCODE2);
                }
                break;
            case R.id.rlCheckType:
                //检测类型
                Intent intent3=new Intent(TemporaryTask.this, ActivityCheckTypeList.class);
                intent3.putExtra("flag", REQUESTCODE3);
                startActivityForResult(intent3, REQUESTCODE3);
                break;
            case R.id.rlExcuteDegree:
                //执行岗位
                Intent intent4=new Intent(TemporaryTask.this, ActivityDegreeList.class);
                intent4.putExtra("flag", REQUESTCODE4);
                startActivityForResult(intent4, REQUESTCODE4);
                break;
            case R.id.rlJoinPerson:
                //参与人员
                Intent intent5=new Intent(TemporaryTask.this, ActivityUserList.class);
                intent5.putExtra("flag", REQUESTCODE5);
                startActivityForResult(intent5, REQUESTCODE5);
                break;
            case R.id.rlCheckTable:
                //检查表
                Intent intent6=new Intent(TemporaryTask.this, ActivityCheckTableList.class);
                intent6.putExtra("flag", REQUESTCODE6);
                startActivityForResult(intent6, REQUESTCODE6);
                break;
        }
    }


    public void submitData(){
        JSONObject jsonObject=new JSONObject();
        if (endTime.equals("")){
            Toast.makeText(TemporaryTask.this,"请选择结束时间！！！",Toast.LENGTH_SHORT).show();
            return;
        }
        if (startTime.equals("")){
            Toast.makeText(TemporaryTask.this,"请选择开始时间！！！",Toast.LENGTH_SHORT).show();
            return;
        }
        if (checkGroup.equals("")){
            Toast.makeText(TemporaryTask.this,"请选择执行单位！！！",Toast.LENGTH_SHORT).show();
            return;
        }
        if (defName.equals("")){
            Toast.makeText(TemporaryTask.this,"请填写任务名称！！！",Toast.LENGTH_SHORT).show();
            return;
        }
        if (checkPerson.equals("")){
            Toast.makeText(TemporaryTask.this,"请选择执行人员！！！",Toast.LENGTH_SHORT).show();
            return;
        }

        if (defDesc.equals("")){
            Toast.makeText(TemporaryTask.this,"请填写任务描述！！！",Toast.LENGTH_SHORT).show();
            return;
        }
        if (checkParticipant.equals("")){
            Toast.makeText(TemporaryTask.this,"请选择参与人员！！！",Toast.LENGTH_SHORT).show();
            return;
        }
        if (checkType.equals("")){
            Toast.makeText(TemporaryTask.this,"请选择检查类型！！！",Toast.LENGTH_SHORT).show();
            return;
        }
        if (checkPosition.equals("")){
            Toast.makeText(TemporaryTask.this,"请选择执行岗位！！！",Toast.LENGTH_SHORT).show();
            return;
        }
        if (checkTable.equals("")){
            Toast.makeText(TemporaryTask.this,"请选择检查表！！！",Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            jsonObject.put("endTime",endTime);
            jsonObject.put("startTime",startTime);
            jsonObject.put("checkGroup",checkGroup);
            jsonObject.put("examinedGroup",examinedGroup);
            jsonObject.put("defName",defName);
            jsonObject.put("checkModel",checkModel);
            jsonObject.put("checkPerson",checkPerson);
            jsonObject.put("defDesc",defDesc);
            jsonObject.put("checkParticipant",checkParticipant);
            jsonObject.put("checkType",checkType);
            jsonObject.put("checkPosition",checkPosition);
            jsonObject.put("checkTable",checkTable);
        } catch (JSONException e) {
            e.printStackTrace();
        }


        new HttpRequest(this).doPost(UrlConstants.publishTemporaryTask, null, jsonObject,new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            Toast.makeText(TemporaryTask.this,"发布临时任务成功",Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }else {
                        Toast.makeText(TemporaryTask.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }



    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.temporary_task;
    }

    @Override
    protected void initView() {
        setTitleText("发布临时任务");
        rlStartTime=findViewById(R.id.rlStartTime);
        tvPublish=findViewById(R.id.tvPublish);
        rlEndTime=findViewById(R.id.rlEndTime);
        rlExcuteUnit=findViewById(R.id.rlExcuteUnit);
        tvSceneTask=findViewById(R.id.tvSceneTask);
        tvCheckedPart=findViewById(R.id.tvCheckedPart);
        tvFoundationTask=findViewById(R.id.tvFoundationTask);
        tvExcuteUnit=findViewById(R.id.tvExecuteUnit);
        rlCheckedDePart=findViewById(R.id.rlCheckedDePart);
        rlExcuteDegree=findViewById(R.id.rlExcuteDegree);
        tvStartTime=findViewById(R.id.tvStartTime);
        tvCheckTable=findViewById(R.id.tvCheckTable);
        tvEndTime=findViewById(R.id.tvEndTime);
        etTaskName=findViewById(R.id.etTaskName);
        tvJoinPerson=findViewById(R.id.tvJoinPerson);
        tvExcuteUnitDegree=findViewById(R.id.tvExcuteUnitDegree);
        tvExcuteUnitPerson=findViewById(R.id.tvExcuteUnitPerson);
        etTaskIntro=findViewById(R.id.etTaskIntro);
        rlExcuteUnitPerson=findViewById(R.id.rlExcuteUnitPerson);
        rlJoinPerson=findViewById(R.id.rlJoinPerson);
        rlCheckType=findViewById(R.id.rlCheckType);
        rlCheckTable=findViewById(R.id.rlCheckTable);
        tvCheckType=findViewById(R.id.tvCheckType);
        rlCheckTable.setOnClickListener(this::onClick);
        rlJoinPerson.setOnClickListener(this::onClick);
        rlExcuteUnitPerson.setOnClickListener(this::onClick);
        rlCheckType.setOnClickListener(this::onClick);
        rlCheckedDePart.setOnClickListener(this::onClick);
        tvCheckedPart.setOnClickListener(this::onClick);
        tvFoundationTask.setOnClickListener(this::onClick);
        tvPublish.setOnClickListener(this::onClick);
        rlStartTime.setOnClickListener(this::onClick);
        rlExcuteUnit.setOnClickListener(this::onClick);
        rlEndTime.setOnClickListener(this::onClick);
        tvSceneTask.setOnClickListener(this::onClick);
        rlExcuteDegree.setOnClickListener(this::onClick);


        etTaskName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                defName=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etTaskIntro.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                defDesc=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            if (requestCode==REQUESTCODE){
                checkGroup=data.getStringExtra("id");
                tvExcuteUnit.setText(data.getStringExtra("name"));
            } else if(requestCode==REQUESTCODE1){
                examinedGroup=data.getStringExtra("id");
                tvCheckedPart.setText(data.getStringExtra("name"));
            } else if(requestCode==REQUESTCODE2){
                tvExcuteUnitPerson.setText(data.getStringExtra("name"));
                checkPerson=data.getStringExtra("id");
            } else if(requestCode==REQUESTCODE3){
                tvCheckType.setText(data.getStringExtra("name"));
                checkType=data.getStringExtra("id");
            } else if(requestCode==REQUESTCODE4){
                tvExcuteUnitDegree.setText(data.getStringExtra("name"));
                checkPosition=data.getStringExtra("id");
            } else if(requestCode==REQUESTCODE5){
                tvJoinPerson.setText(data.getStringExtra("name"));
                checkParticipant=data.getStringExtra("id");
            } else if(requestCode==REQUESTCODE6){
                tvCheckTable.setText(data.getStringExtra("name"));
                checkTable=data.getStringExtra("id");
            }
//
//            else if (requestCode== PictureConfig.CHOOSE_REQUEST) {
//                // 结果回调
//                //获取oss  token
//                List<LocalMedia> cameraList = PictureSelector.obtainMultipleResult(data);
//                imagesUrl.clear();
//                for (int i = 0; i < cameraList.size(); i++) {
//                    imagesUrl.add(cameraList.get(i));
//                }
//                adapter.notifyDataSetChanged();
//            }
        }
    }


    public void reSetStatus(){
        tvFoundationTask.setBackgroundResource(R.drawable.stoke_gray_bg_5);
        tvSceneTask.setBackgroundResource(R.drawable.stoke_gray_bg_5);
        tvSceneTask.setTextColor(getResources().getColor(R.color.gray9));
        tvFoundationTask.setTextColor(getResources().getColor(R.color.gray9));
    }

    @Override
    protected void initData() { }

    @Override
    protected int getTitleBarType() {
        return 0;
    }
}